package io.github.lee.jel.ui.main

import android.os.Build
import android.os.Bundle
import android.window.OnBackInvokedDispatcher
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import dagger.hilt.android.AndroidEntryPoint
import io.github.lee.core.ui.BaseActivity
import io.github.lee.jel.R
import io.github.lee.jel.databinding.ActivityMainBinding
import io.github.lee.jel.global.theme.ThemeManager

private const val CLICK_TIME_DIFF = 3000L

@AndroidEntryPoint
class MainActivity : BaseActivity<ActivityMainBinding, MainVM>() {

    private var preClickTime = 0L

    override fun onCreateViewModel(): Lazy<MainVM> =
        viewModels()

    override fun onCreateSuccess(): ActivityMainBinding =
        ActivityMainBinding.inflate(layoutInflater)

    //===Desc:=============================================================

    override fun onInitData(savedInstanceState: Bundle?) {
        super.onInitData(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            onBackInvokedDispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT) {
                clickToExit()
            }
        } else {
            onBackPressedDispatcher.addCallback(this@MainActivity,
                object : OnBackPressedCallback(true) {
                    override fun handleOnBackPressed() {
                        clickToExit()
                    }

                })
        }
    }

    override fun onSetViewData() {
        super.onSetViewData()
        statusBarColor(
            ThemeManager.statusBarColor(mContext),
            ThemeManager.isStatusBarDark()
        )
        navigationBarColor(ThemeManager.statusBarColor(mContext))

        vb?.vpContent?.adapter = MainPageAdapter(this)
    }


    //===Desc:=============================================================
    private fun clickToExit() {
        val now = System.currentTimeMillis()
        if (now - preClickTime > CLICK_TIME_DIFF) {
            toast(getString(R.string.txt_click_exit))
            preClickTime = now
        } else {
            finish()
        }
    }

}